package cemp.schedule;

import cemp.common.util.DateUtil;
import cemp.entity.DailyTask;
import cemp.entity.StockSysUser;
import cemp.mapper.DailyTaskMapper;
import cemp.mapper.StockSysUserMapper;
import cemp.service.DailyTaskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * @author xshibai
 * @date 2025年07月27日 11:08
 */
@Component
@RequiredArgsConstructor
public class SheculeJob {
    private final DailyTaskMapper dailyTaskMapper;
    private final DailyTaskService dailyTaskService;
    private final StockSysUserMapper stockSysUserMapper;

    @XxlJob("stockDailyJob")
    public void stockTaskJobHandler() throws Exception {
        System.out.println("stockDailyJob");
    }

    @XxlJob("dailyTaskSta")
    public void dailyTaskSta() throws Exception {
        System.out.println("dailyTaskSta task begin");
        //查询所有用户
        List<StockSysUser> users=  stockSysUserMapper.selectList(null);
        users.forEach(new Consumer<StockSysUser>() {
            @Override
            public void accept(StockSysUser user) {
                //打分
                LambdaQueryWrapper<DailyTask> lqw = new LambdaQueryWrapper<>();
                lqw.eq(DailyTask::getUserid,user.getId());
                lqw.gt(DailyTask::getCreateDate, DateUtil.localDate2Str(LocalDate.now()));
                lqw.orderByDesc(DailyTask::getCreateDate);
                List<DailyTask> dailyTasks =  dailyTaskMapper.selectList(lqw);
                if(dailyTasks != null && dailyTasks.size()> 0){
                    BigDecimal totalScores =  dailyTasks.stream().map(DailyTask::getScore).map(BigDecimal::valueOf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal completeScores =  dailyTasks.stream().filter(t -> t.getCompleted() ==1).map(DailyTask::getScore).map(BigDecimal::valueOf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal result = completeScores.multiply(BigDecimal.valueOf(100)).divide(totalScores,2, RoundingMode.HALF_UP);
                    //发消息
                    dailyTaskService.sendMsg(user.getId(),result);
                }
            }
        });

    }


}
